/*
 * Copyright 2017 StreamSets Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.streamsets.pipeline.lib.udp;

import com.streamsets.pipeline.api.impl.Utils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;

public class UDPMessageDeserializer {

  public UDPMessageDeserializer() {
  }

  public UDPMessage deserialize(byte[] buffer) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
    ObjectInputStream ois = new ObjectInputStream(bais);
    int version = ois.readInt();
    if (version == UDPConstants.UDP_MESSAGE_VERSION) {
      int type = ois.readInt();
      long received = ois.readLong();
      String address = ois.readUTF();
      int port = ois.readInt();
      InetSocketAddress sender = new InetSocketAddress(address, port);
      address = ois.readUTF();
      port = ois.readInt();
      InetSocketAddress receiver = new InetSocketAddress(address, port);
      int dataLen = ois.readInt();
      byte[] data = new byte[dataLen];
      ois.readFully(data);
      ois.close();
      ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
      DatagramPacket datagram = new DatagramPacket(byteBuf, receiver, sender);
      return new UDPMessage(type, received, datagram);
    } else {
      throw new IOException(Utils.format("Unsupported version '{}'", version));
    }
  }

}
